import React, { useEffect, useState } from 'react';
import { Modal, Form, Input, Select, InputNumber, TreeSelect, message } from 'antd';
import { createCategory, updateCategory, getCategoryList } from '@/services/courseManagementApi';

interface CategoryFormProps {
  visible: boolean;
  mode: 'create' | 'edit';
  initialValues?: COURSE.CategoryModel;
  onCancel: () => void;
  onSuccess: () => void;
}

const CategoryForm: React.FC<CategoryFormProps> = ({
  visible,
  mode,
  initialValues,
  onCancel,
  onSuccess,
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [categoryTree, setCategoryTree] = useState<any[]>([]);

  useEffect(() => {
    if (visible) {
      loadCategoryTree();
      if (mode === 'edit' && initialValues) {
        form.setFieldsValue(initialValues);
      } else {
        form.resetFields();
        // 如果有预设的父分类ID，设置到表单中
        if (initialValues?.parent_id) {
          form.setFieldsValue({ parent_id: initialValues.parent_id });
        }
      }
    }
  }, [visible, mode, initialValues, form]);

  // 加载分类树
  const loadCategoryTree = async () => {
    try {
      const response = await getCategoryList({ page: 1, limit: 1000 });
      const categories = response.data.list;
      
      // 构建树形结构
      const buildTree = (parentId: number | null = null): any[] => {
        return categories
          .filter(cat => {
            // 编辑模式下，排除当前分类及其子分类
            if (mode === 'edit' && initialValues) {
              return cat.parent_id === parentId && cat.id !== initialValues.id;
            }
            return cat.parent_id === parentId;
          })
          .map(cat => ({
            title: cat.name,
            value: cat.id,
            key: cat.id,
            children: buildTree(cat.id),
          }));
      };

      setCategoryTree(buildTree());
    } catch (error) {
      console.error('加载分类树失败:', error);
    }
  };

  // 处理表单提交
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);

      if (mode === 'create') {
        await createCategory(values);
        message.success('分类创建成功');
      } else {
        await updateCategory(initialValues!.id, values);
        message.success('分类更新成功');
      }

      onSuccess();
    } catch (error) {
      message.error(mode === 'create' ? '分类创建失败' : '分类更新失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Modal
      title={mode === 'create' ? '新建分类' : '编辑分类'}
      open={visible}
      onCancel={onCancel}
      onOk={handleSubmit}
      confirmLoading={loading}
      width={600}
      destroyOnClose
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={{
          status: 'active',
          sort_order: 0,
        }}
      >
        <Form.Item
          name="name"
          label="分类名称"
          rules={[
            { required: true, message: '请输入分类名称' },
            { max: 50, message: '分类名称不能超过50个字符' },
          ]}
        >
          <Input placeholder="请输入分类名称" />
        </Form.Item>

        <Form.Item
          name="description"
          label="分类描述"
          rules={[
            { max: 200, message: '分类描述不能超过200个字符' },
          ]}
        >
          <Input.TextArea
            rows={3}
            placeholder="请输入分类描述"
            showCount
            maxLength={200}
          />
        </Form.Item>

        <Form.Item
          name="parent_id"
          label="父分类"
        >
          <TreeSelect
            placeholder="请选择父分类，不选择则为顶级分类"
            allowClear
            treeData={categoryTree}
            treeDefaultExpandAll
            showSearch
            treeNodeFilterProp="title"
          />
        </Form.Item>

        <Form.Item
          name="sort_order"
          label="排序"
          rules={[
            { type: 'number', min: 0, message: '排序值不能为负数' },
          ]}
        >
          <InputNumber
            style={{ width: '100%' }}
            placeholder="请输入排序值，数字越小越靠前"
            min={0}
          />
        </Form.Item>

        <Form.Item
          name="status"
          label="状态"
          rules={[{ required: true, message: '请选择状态' }]}
        >
          <Select placeholder="请选择状态">
            <Select.Option value="active">启用</Select.Option>
            <Select.Option value="inactive">禁用</Select.Option>
          </Select>
        </Form.Item>

        <Form.Item
          name="icon"
          label="分类图标"
        >
          <Input placeholder="请输入图标类名或图标URL" />
        </Form.Item>

        <Form.Item
          name="color"
          label="分类颜色"
        >
          <Input
            type="color"
            placeholder="请选择分类颜色"
            style={{ width: 100 }}
          />
        </Form.Item>

        <Form.Item
          name="keywords"
          label="关键词"
        >
          <Select
            mode="tags"
            placeholder="请输入关键词，用于搜索和SEO"
            style={{ width: '100%' }}
          />
        </Form.Item>

        <Form.Item
          name="seo_title"
          label="SEO标题"
          rules={[
            { max: 100, message: 'SEO标题不能超过100个字符' },
          ]}
        >
          <Input placeholder="请输入SEO标题" />
        </Form.Item>

        <Form.Item
          name="seo_description"
          label="SEO描述"
          rules={[
            { max: 200, message: 'SEO描述不能超过200个字符' },
          ]}
        >
          <Input.TextArea
            rows={2}
            placeholder="请输入SEO描述"
            showCount
            maxLength={200}
          />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default CategoryForm;
